<template>
  <div style="width: 100%; height: 100%; overflow: hidden">
    <LiveRoom v-if="flag" :list="list" :config="config" interactive/>
    <div v-else class="shadow-font danger_msg">
      {{ translate('直播弹幕离线中') }}
    </div>
  </div>
</template>

<script setup>
import {inject, onMounted, ref} from 'vue'
import LiveRoom from '@/components/live-room'
import WebsocketClient from '@/assets/websocket.js'
import {ElNotification} from 'element-plus'

const router = inject('router')
const getRandomColor = inject('getRandomColor')
const translate = inject('translate') // 翻译
const config = ref({})
const list = ref([]) // 弹幕数据列表
const flag = ref(false) // 直播转发状态

const client = new WebsocketClient() // 创建ws客户端
// 连接成功
client.registerCallBack('onopen', () => {
  console.log('onopen')
})
// 连接关闭
client.registerCallBack('onclose', () => {
  console.log('onclose')
  flag.value = client.connected
  ElNotification({
    title: 'ERROR',
    message: translate('监听断开，请检查日志'),
    type: 'error',
    showClose: false,
    duration: 0
  })
})
// 接收消息
client.registerCallBack('onmessage', ev => {
  console.log('onmessage')
  flag.value = true
  const copyList = JSON.parse(JSON.stringify(list.value))
  let arr = JSON.parse(ev.data)
  for (let item of arr) {
    if (item.cmd === 'SYS_CONF') {
      let data = item.data
      data.display = JSON.parse(data.display)
      data.shield = JSON.parse(data.shield)
      config.value = data
      continue
    }
    item.key = Math.random()
    if (config.value['shield'].user.includes(item['username'])) return
    if (item.cmd === 'WELCOME' && config.value['display']['welcome'] ||
        item.cmd === 'MSG' && config.value['display']['chat'] ||
        item.cmd === 'SC' && config.value['display']['sc'] ||
        item.cmd === 'VIP' && config.value['display']['gift']) copyList.push(item)
    while (copyList.length > 32) copyList.shift()
    list.value = copyList
  }
})

onMounted(() => {
  const confId = router.currentRoute.value.query['confId']
  request({
    url: 'conf',
    method: 'GET',
    params: {id: confId}
  }).then(res => {
    let data = res.data.data
    data.display = JSON.parse(data.display)
    data.shield = JSON.parse(data.shield)
    config.value = data
    setTimeout(() => {
      !client.connected && client.connect('ws://127.0.0.1:20100/sub?confId=' + confId)
    }, 2000)
  })
})
</script>

<style scoped>
.danger_msg {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 16vh;
  background: var(--z-note-color);
  color: var(--z-red-color);
  font-size: 3.2rem;
  font-weight: bold;
  letter-spacing: .2rem;
}
</style>